<script setup lang="ts">
import { ref } from 'vue'
import { useToast } from 'wot-design-uni'
// import { useTokenStore } from '@/store/token'
// import { parseUrlToObj } from '@/utils/index'
import { useUserStore } from '@/store'

const userStore = useUserStore()
const toast = useToast()

// 页面配置
definePage({
  style: {
    navigationBarTitleText: '登录',
    navigationStyle: 'custom',
  },
})

// const tokenStore = useTokenStore()

// 页面模式：login 或 register
const pageMode = ref<'login' | 'register'>('login')
const showPassword = ref(false)
const showConfirmPassword = ref(false)
const isLoading = ref(false)
// 添加验证码倒计时状态
const countdown = ref(0)
let countdownTimer: number | null = null

// 表单数据
const loginForm = ref({
  username: '',
  password: '',
  captcha: '',
})

const registerForm = ref({
  username: '',
  password: '',
  confirmPassword: '',
  phone: '',
  captcha: '',
})

// 获取页面参数，处理重定向
function handleRedirect() {
  uni.switchTab({ url: '/pages/index/index' })
}

// 切换登录/注册模式
function switchMode() {
  pageMode.value = pageMode.value === 'login' ? 'register' : 'login'
}

// 获取验证码
async function getCaptcha() {
  // 验证手机号格式
  if (!registerForm.value.phone || !/^1[3-9]\d{9}$/.test(registerForm.value.phone)) {
    return uni.showToast({ title: '请输入正确的手机号', icon: 'none' })
  }

  try {
    isLoading.value = true
    const res = await uni.request({
      url: 'http://192.168.1.190:8000/jiaozuo/apilocate/user/sendMsg',
      method: 'POST',
      data: {
        phone: registerForm.value.phone,
      },
    })
    console.log('获取验证码响应:', res)

    // 调用获取验证码的API成功后开始倒计时
    startCountdown()

    uni.showToast({ title: '验证码已发送', icon: 'success' })
  }
  catch (error) {
    console.error('获取验证码失败:', error)
    uni.showToast({ title: '获取验证码失败', icon: 'error' })
  }
  finally {
    isLoading.value = false
  }
}

// 开始倒计时函数
function startCountdown() {
  // 清除之前的定时器
  if (countdownTimer) {
    clearInterval(countdownTimer)
  }

  countdown.value = 60

  // 设置新的定时器
  countdownTimer = window.setInterval(() => {
    countdown.value--

    // 倒计时结束
    if (countdown.value <= 0) {
      if (countdownTimer) {
        clearInterval(countdownTimer)
        countdownTimer = null
      }
      countdown.value = 0
    }
  }, 1000)
}

// 处理登录
async function handleLogin() {
  if (!loginForm.value.username) {
    return uni.showToast({ title: '请输入手机号', icon: 'none' })
  }
  if (!loginForm.value.password) {
    return uni.showToast({ title: '请输入密码', icon: 'none' })
  }
  isLoading.value = true
  toast.loading({ msg: '登录中' })
  // 登录逻辑保持不变
  const res = await uni.request({
    url: 'http://192.168.1.190:8000/jiaozuo/apilocate/masterApi/apiLogin',
    method: 'POST',
    data: {
      userName: loginForm.value.username, // 手机号
      passWord: loginForm.value.password, // 密码
      zhuanjiaFlag: '1', // 专家标识
    },
  })
  console.log('登录响应:', res)
  if (res.data.code === 1) {
    toast.success('登录成功')
    isLoading.value = false
    const userInfo = res.data.info
    userStore.setUserInfo({
      userId: userInfo.id,
      username: userInfo.phoneNumber,
      nickname: userInfo.nickName,
      avatar: '/static/images/default-avatar.png',
    })
    // 保存用户信息到本地存储
    uni.setStorageSync('user', userInfo)
    setTimeout(() => {
      handleRedirect()
    }, 1000)
  }
  else {
    toast.error(res.msg || '登录失败')
    isLoading.value = false
  }
}

// 处理注册
async function handleRegister() {
  // 注册逻辑保持不变
  // 表单验证
  if (!registerForm.value.username) {
    return uni.showToast({ title: '请输入用户名', icon: 'none' })
  }
  if (!registerForm.value.phone) {
    return uni.showToast({ title: '请输入手机号', icon: 'none' })
  }
  if (!registerForm.value.captcha) {
    return uni.showToast({ title: '请输入验证码', icon: 'none' })
  }
  if (!registerForm.value.password) {
    return uni.showToast({ title: '请设置密码', icon: 'none' })
  }
  if (registerForm.value.password !== registerForm.value.confirmPassword) {
    return uni.showToast({ title: '两次输入的密码不一致', icon: 'none' })
  }

  try {
    isLoading.value = true
    // console.log('注册表单数据:', registerForm.value)
    const params = {
      name: registerForm.value.username,
      again: registerForm.value.password,
      phone: registerForm.value.phone,
      code: registerForm.value.captcha,
      zhuanjiaFlag: '1', // 专家标识
    }
    console.log('注册参数:', params)
    // 调用注册API
    const res = await uni.request({
      url: 'http://192.168.1.190:8000/jiaozuo/apilocate/masterApi/doRegister',
      method: 'POST',
      data: params,
    })
    console.log('注册响应:', res)
    uni.showToast({ title: '注册成功', icon: 'success' })

    // 注册成功后切换到登录模式
    setTimeout(() => {
      pageMode.value = 'login'
      // 填充用户名到登录表单
      loginForm.value.username = registerForm.value.username
    }, 500)
  }
  catch (error) {
    console.error('注册失败:', error)
    uni.showToast({ title: '注册失败，请重试', icon: 'error' })
  }
  finally {
    isLoading.value = false
  }
}

// 忘记密码
function forgotPassword() {
  // 实际项目中实现忘记密码逻辑
  uni.showToast({ title: '忘记密码功能开发中', icon: 'none' })
}
</script>

<template>
  <view class="login min-h-screen bg-gray-50">
    <!-- 自定义导航栏 -->
    <view class="sticky top-0 z-10 bg-white px-4 py-3 text-center shadow-sm">
      <view class="text-lg text-gray-800 font-medium">
        登录
      </view>
    </view>
    <view class="px-4 py-8">
      <!-- 登录/注册标题 -->
      <view class="mb-8 text-center">
        <view class="text-3xl text-gray-800 font-bold">
          {{ pageMode === 'login' ? '用户登录' : '用户注册' }}
        </view>
        <view class="mt-2 text-sm text-gray-500">
          {{ pageMode === 'login' ? '欢迎回来，请登录您的账号' : '创建新账号，开始使用服务' }}
        </view>
      </view>

      <!-- 登录/注册表单 -->
      <view class="rounded-lg bg-white p-6 shadow-sm">
        <!-- 登录表单 -->
        <template v-if="pageMode === 'login'">
          <!-- 用户名输入框 -->
          <view class="mb-4">
            <view class="mb-2 text-sm text-gray-700 font-medium">
              手机号
            </view>
            <input
              v-model="loginForm.username" type="text" placeholder="请输入手机号" :disabled="isLoading"
              class="w-full border border-gray-300 rounded-lg px-4 py-3 text-base focus:border-blue-500 focus:outline-none"
            >
          </view>

          <!-- 密码输入框 -->
          <view class="mb-6">
            <view class="mb-2 text-sm text-gray-700 font-medium">
              密码
            </view>
            <view class="relative">
              <input
                v-model="loginForm.password" :type="showPassword ? 'text' : 'password'"
                placeholder="请输入密码" :disabled="isLoading"
                class="w-full border border-gray-300 rounded-lg px-4 py-3 text-base focus:border-blue-500 focus:outline-none"
              >
              <view
                class="absolute right-3 top-1/2 transform cursor-pointer text-gray-400 -translate-y-1/2"
                @click="showPassword = !showPassword"
              >
                {{ showPassword ? '隐藏' : '显示' }}
              </view>
            </view>
          </view>

          <!-- 登录按钮 -->
          <button
            :disabled="isLoading" :class="isLoading ? 'bg-gray-400' : 'bg-blue-500'"
            class="mb-4 w-full rounded-lg py-3 text-base text-white font-medium" @click="handleLogin"
          >
            {{ isLoading ? '登录中...' : '登录' }}
          </button>

          <!-- 注册按钮 -->
          <button
            class="w-full border border-blue-500 rounded-lg bg-white py-3 text-base text-blue-500 font-medium"
            :disabled="isLoading" @click="switchMode"
          >
            注册账号
          </button>
        </template>

        <!-- 注册表单 -->
        <template v-else>
          <!-- 用户名输入框 -->
          <view class="mb-4">
            <view class="mb-2 text-sm text-gray-700 font-medium">
              用户名
            </view>
            <input
              v-model="registerForm.username" type="text" placeholder="请设置用户名" :disabled="isLoading"
              class="w-full border border-gray-300 rounded-lg px-4 py-3 text-base focus:border-blue-500 focus:outline-none"
            >
          </view>

          <!-- 手机号输入框 -->
          <view class="mb-4">
            <view class="mb-2 text-sm text-gray-700 font-medium">
              手机号
            </view>
            <input
              v-model="registerForm.phone" type="number" placeholder="请输入手机号" :disabled="isLoading"
              class="w-full border border-gray-300 rounded-lg px-4 py-3 text-base focus:border-blue-500 focus:outline-none"
            >
          </view>

          <!-- 验证码输入框 -->
          <view class="mb-4">
            <view class="mb-2 text-sm text-gray-700 font-medium">
              验证码
            </view>
            <view class="flex gap-2">
              <input
                v-model="registerForm.captcha" type="number" placeholder="请输入验证码"
                :disabled="isLoading"
                class="flex-1 border border-gray-300 rounded-lg px-4 py-3 text-base focus:border-blue-500 focus:outline-none"
              >
              <button
                :disabled="isLoading || !registerForm.phone || countdown > 0"
                :class="{
                  'bg-blue-500': countdown === 0,
                  'bg-gray-400': countdown > 0,
                }"
                class="whitespace-nowrap border rounded-lg px-4 py-3 text-sm text-white font-medium"
                @click="getCaptcha"
              >
                {{ countdown > 0 ? `${countdown}秒后重新获取` : '获取验证码' }}
              </button>
            </view>
          </view>

          <!-- 密码输入框 -->
          <view class="mb-4">
            <view class="mb-2 text-sm text-gray-700 font-medium">
              设置密码
            </view>
            <view class="relative">
              <input
                v-model="registerForm.password" :type="showPassword ? 'text' : 'password'"
                placeholder="请设置密码" :disabled="isLoading"
                class="w-full border border-gray-300 rounded-lg px-4 py-3 text-base focus:border-blue-500 focus:outline-none"
              >
              <view
                class="absolute right-3 top-1/2 transform cursor-pointer text-gray-400 -translate-y-1/2"
                @click="showPassword = !showPassword"
              >
                {{ showPassword ? '隐藏' : '显示' }}
              </view>
            </view>
          </view>

          <!-- 确认密码输入框 -->
          <view class="mb-6">
            <view class="mb-2 text-sm text-gray-700 font-medium">
              确认密码
            </view>
            <view class="relative">
              <input
                v-model="registerForm.confirmPassword"
                :type="showConfirmPassword ? 'text' : 'password'" placeholder="请再次输入密码"
                :disabled="isLoading"
                class="w-full border border-gray-300 rounded-lg px-4 py-3 text-base focus:border-blue-500 focus:outline-none"
              >
              <view
                class="absolute right-3 top-1/2 transform cursor-pointer text-gray-400 -translate-y-1/2"
                @click="showConfirmPassword = !showConfirmPassword"
              >
                {{ showConfirmPassword ? '隐藏' : '显示' }}
              </view>
            </view>
          </view>

          <!-- 注册按钮 -->
          <button
            :disabled="isLoading" :class="isLoading ? 'bg-gray-400' : 'bg-blue-500'"
            class="mb-4 w-full rounded-lg py-3 text-base text-white font-medium" @click="handleRegister"
          >
            {{ isLoading ? '注册中...' : '注册' }}
          </button>

          <!-- 登录按钮 -->
          <button
            class="w-full border border-blue-500 rounded-lg bg-white py-3 text-base text-blue-500 font-medium"
            :disabled="isLoading" @click="switchMode"
          >
            已有账号，去登录
          </button>
        </template>
      </view>

      <!-- 忘记密码 -->
      <view v-if="pageMode === 'login'" class="mt-6 text-center">
        <view class="inline-block text-sm text-gray-500">
          <text class="cursor-pointer text-blue-500" @click="forgotPassword">忘记密码？</text>
        </view>
      </view>
    </view>
  </view>
</template>

<style lang="scss" scoped>
// 由于使用了UNOCSS，大部分样式已通过原子化类名实现
// 仅保留必要的自定义样式
</style>
